package com.ipan.kits.io;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.imageio.ImageIO;

/**
 * 图片工具类
 * 
 * @author iPan
 * @version 2017-05-04
 */
public class ImageUtil {

	public static void compressToFile(String srcFile, String descFile, int width, int height) {
		String kzm = descFile.substring(descFile.lastIndexOf(".") + 1);
		if (kzm == "") {
			return ;
		}
		
		FileOutputStream fout = null;
		try {
			BufferedImage image = compress(srcFile, width, height);
			fout = new FileOutputStream(new File(descFile)); 
			ImageIO.write(image, kzm, fout);
		} catch (Exception e) {
			new RuntimeException("压缩图片出错", e);
		} finally {
			if (fout != null) {
				try {
					fout.close();
				} catch (IOException e) {
				}
			}
		}
	}
	
	public static BufferedImage compress(String srcFile, int width, int height) {
		FileInputStream fin = null;
		BufferedImage image = null;
		try {
			fin = new FileInputStream(new File(srcFile));		
			BufferedImage inBuf = ImageIO.read(fin);
			int ww = inBuf.getWidth();
			int hh = inBuf.getHeight();
			float num0 = (float) ww / (float) hh;
			float num1 = (float) width / (float) height;
			float num;
			if (num0 > num1) { // 实际图片比目标图片大
			    num = (float) ww / (float) width;
			    ww = width;
			    num = (float) hh / num;
			    hh = (int) num;
			} else { // 实际图片比目标图片小
			    num = (float) hh / (float) height;
			    hh = height;
			    num = (float) ww / num;
			    ww = (int) num;
			}
			
			image = new BufferedImage(ww, hh, BufferedImage.SCALE_SMOOTH); 		
			image.getGraphics().drawImage(inBuf, 0, 0, ww, hh, null); // 绘制缩小后的图
		} catch (Exception e) {
			new RuntimeException("压缩图片出错", e);
		} finally {
			if (fin != null) {
				try {
					fin.close();
				} catch (IOException e) {
				}
			}
		}
		return image;
	}	
	
}
